package com.niit.service.impl;

import com.niit.entity.Info;
import com.niit.entity.Job;
import com.niit.entity.User;
import com.niit.repository.JobRepository;
import com.niit.service.JobService;
import jakarta.persistence.criteria.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class JobServiceImpl implements JobService {

    @Autowired
    private JobRepository jobRepository;



    @Override
    public void addJob(Job job) {
        jobRepository.save(job);
    }

    @Override
    public void updateJob(Job job) {
        jobRepository.save(job);
    }

    @Override
    public void deleteJob(Integer id) {
        jobRepository.deleteById(id);
    }

    @Override
    public Job getJob(Integer id) {
        return jobRepository.findById(id).orElseThrow(()->new RuntimeException("未找到该职位"));
    }

    @Override
    public List<Job> getAllJobs() {
        return jobRepository.findAll();
    }

    @Override
    public List<Job> getMyJobs(User user) {
        return jobRepository.findByUser(user);
    }

    @Override
    public int getJobCount(User user) {
        return jobRepository.countByUser(user);
    }

    @Override
    public List<Job> searchJob(String keyword) {
        return jobRepository.searchByKeyword(keyword);
    }

    @Override
    public Page<Job> getAllJobsByPage(Pageable pageable) {
        return jobRepository.findAll(pageable);
    }

    @Override
    public void auditJob(Integer id, Byte status) {
        // 根据ID查找职位
        Job job = jobRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("职位不存在"));

        // 更新职位状态
        job.setStatus(status);

        // 保存更新后的职位信息
        jobRepository.save(job);
    }


    @Override
    public Page<Job> getJobsByCondition( String title, String publishUser, Byte status, Pageable pageable) {
        return jobRepository.findAll(new Specification<Job>() {
            @Override
            public Predicate toPredicate(Root<Job> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                // 使用 Jakarta Persistence 的 Predicate 类型
                List<Predicate> predicates = new ArrayList<>();

                // 职位标题模糊查询
                if (StringUtils.hasText(title)) {
                    predicates.add(cb.like(root.get("title"), "%" + title + "%"));
                }

                // 状态查询
                if (status != null) {
                    predicates.add(cb.equal(root.get("status"), status));
                }

                // 发布者姓名查询
                if (StringUtils.hasText(publishUser)) {
                    // 关联 Job -> User
                    Join<Job, User> userJoin = root.join("user", JoinType.INNER);

                    // 关联 User -> Info
                    Join<User, Info> infoJoin = userJoin.join("info", JoinType.INNER);

                    // 创建OR条件：同时匹配真实姓名和用户名
                    Predicate realNamePred = cb.like(infoJoin.get("realName"), "%" + publishUser + "%");
                    Predicate userNamePred = cb.like(infoJoin.get("username"), "%" + publishUser + "%");

                    // 添加OR组合条件
                    predicates.add(cb.or(realNamePred, userNamePred));
                }

                // 组合所有条件
                return cb.and(predicates.toArray(new Predicate[0]));
            }
        }, pageable);
    }


    @Override
    public Page<Job> findJobsByCondition(String location, String salaryRange, String keyword, Pageable pageable) {
        Specification<Job> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 只查询审核通过的职位
            predicates.add(cb.equal(root.get("status"), 1));

            if (StringUtils.hasText(location)) {
                predicates.add(cb.like(root.get("location"), "%" + location + "%"));
            }
            if (StringUtils.hasText(salaryRange)) {
                predicates.add(cb.equal(root.get("salaryRange"), salaryRange));
            }
            if (StringUtils.hasText(keyword)) {
                predicates.add(cb.like(root.get("title"), "%" + keyword + "%"));
            }

            return cb.and(predicates.toArray(new Predicate[0]));
        };

        return jobRepository.findAll(spec, pageable);
    }

    //获取已审核的职位信息
    @Override
    public List<Job> getAuditedJobs() {
        //查找所有职位状态为1的职位
        return jobRepository.findByStatus(1);
    }
}
